<?php

namespace App\Services;

use App\Models\AdminResource;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AdminResourceService extends BaseService
{
    /**
     * 创建资源
     * @param $data
     * @return bool
     */
    public function create($data): bool
    {
        try {
            $result = AdminResource::query()->create($data);
            if ($result) {
                return true;
            }
            return false;
        } catch (\Exception $exception){
            return false;
        }
    }

    /**
     *  根据ID修改资源
     * @param $data
     * @param $id
     * @return bool
     */
    public function updateById($data,$id): bool
    {
        try {
            $result = AdminResource::query()->where('id','=',$id)->update($data);
            if ($result) {
                return true;
            }
            return false;
        }catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * 根据ID查找资源信息
     * @param $id
     * @return array
     */
    public function getById($id): array
    {
        $result = AdminResource::query()->where('id','=',$id)->first();
        if (is_null($result)) {
            return [];
        }
        return $result->toArray();
    }

    /**
     * 根据ID删除资源信息
     * @param $id
     * @return bool
     */
    public function deleteById($id): bool
    {
        try {
            $result = AdminResource::query()->where('id','=',$id)->delete();
            if ($result) {
                return true;
            }
            return false;
        }catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * 分页模糊查询后台资源
     * @param $category_id
     * @param $name
     * @param $url
     * @param $pageSize
     * @param $pageNum
     * @return LengthAwarePaginator
     */
    public function list($category_id,$name,$url,$pageSize,$pageNum): LengthAwarePaginator
    {
        $query = AdminResource::query();
        if ($category_id) {
            $query = $query->where('category_id','=',$category_id);
        }
        if ($name) {
            $query = $query->where('name','like','%'.$name.'%');
        }
        if ($url) {
            $query = $query->where('url','like','%'.$url.'%');
        }
        return $query->paginate($pageSize, ['*'], 'page', $pageNum);
    }

    /**
     *查询所有后台资源
     * @return array
     */
    public function listAll(): array
    {
        $result = AdminResource::query()->get();
        if ($result->count() >0){
            return $result->toArray();
        }
        return [];
    }
}
